package com.xltx.sms.service.impl;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.xltx.sms.properties.AliyunSmsProperties;
import com.xltx.sms.service.AliyunSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author liuyc
 * @ClassName AliyunSmsServiceImpl
 * @Description
 * @Date 2021/12/16 14:27
 */
@Service
public class AliyunSmsServiceImpl implements AliyunSmsService {

    @Autowired
    private AliyunSmsProperties aliyunSmsProperties;

    public IAcsClient getDefaultClient() {
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSmsProperties.getRegionId(),
                aliyunSmsProperties.getAccessKey(), aliyunSmsProperties.getSecretKey());
        return new DefaultAcsClient(profile);
    }

    private CommonRequest request() {
        //创建通用的请求对象
        CommonRequest request = new CommonRequest();
        // 指定请求方式
        request.setSysMethod(MethodType.POST);
        // 短信api的请求地址
        request.setSysDomain(aliyunSmsProperties.getEndpoint());
        //签名算法版本  固定
        request.setSysVersion("2017-05-25");
        //请求 API 的名称
        request.setSysAction("SendSms");
        //指定地域名称
        request.putQueryParameter("RegionId", aliyunSmsProperties.getRegionId());
        return request;
    }


    @Override
    public String sendSms(@NonNull String phoneNumber, @NonNull String signName, @NonNull String templateCode, @NonNull String message) {
        CommonRequest request = this.request();
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        Map<String, Object> params = new HashMap<>(1);
        params.put("code", message);
        request.putQueryParameter("TemplateParam", JSON.toJSONString(params));
        try {
            CommonResponse response = this.getDefaultClient().getCommonResponse(request);
            return response.getData();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String getRandCode(int digits) {
        StringBuilder sBuilder = new StringBuilder();
        Random rd = new Random(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        for (int i = 0; i < digits; ++i) {
            sBuilder.append(rd.nextInt(9));
        }
        return sBuilder.toString();
    }
}
